package com.common.image_loader;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import android.graphics.BitmapFactory;

import com.baidu.common.async_http.AbstractParser;
import com.baidu.common.async_http.AbstractRequester;
import com.baidu.common.net.HttpRequestData;
import com.japher.hackson.response.BaseResponse;
import com.japher.hackson.utils.Tools;

@Deprecated
public class ImageRequest extends AbstractRequester {
	private static final int CORE_POOL_SIZE = 10;
    private static final int MAXIMUM_POOL_SIZE = 100;
    private static final int KEEP_ALIVE = 20;
    
    private static final BlockingQueue<Runnable> sWorkQueue = new LinkedBlockingQueue<Runnable>(10);

    private static final ThreadFactory sThreadFactory = new ThreadFactory() 
    {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
        	Thread t=new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        	t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    };  
  
  
  private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
              MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
	@Override
	protected HttpRequestData createSendData() {
		// TODO Auto-generated method stub
		
		HttpRequestData data = new HttpRequestData();
		data.setUrl(imageUrl);
		data.setGet(true);
		data.setAppUrl(false);
		data.setGzip(false);
		data.setImageRequest(true);
		return data;
	}

	@Override
	protected AbstractParser createParser() {
		// TODO Auto-generated method stub
		ImagePaser p=new ImagePaser(imageUrl);
		
		return p;
	}
	String imageUrl=null;
	public static boolean cacheImage=true;
	public ImageRequest(String imageUrl)
	{
		this.imageUrl=imageUrl;
	}
	
	//private static ThreadPoolImp pool=new ThreadPoolImp(2);
	
	class ImagePaser extends AbstractParser
	{
		public ImagePaser(String url)
		{
			this.url=url;
		}
		protected  BaseResponse parser(String json)
		 {
			 return null;
		}
		@Override
		public BaseResponse parse(InputStream in) {
			// TODO Auto-generated method stub
			
			final ImageResponse imgResponse=new ImageResponse();
			
			if(!cacheImage)
			{
				try 
				{
					imgResponse.image=BitmapFactory.decodeStream(in);
					in.close();
				} 
				catch (IOException e)
				{
					e.printStackTrace();
				}
				
				return imgResponse;
			}
			
			ByteArrayOutputStream out=new ByteArrayOutputStream();
			
			int count = 1024;
			byte []data=null;
			byte []temp=new byte[count];
			
			try 
			{
				int sum=0;
				while(true)
				{
					try 
					{
						int l = in.read(temp);
						if(l>0)
						{
							out.write(temp,0,l);
							publishProgress((sum+=l)*100/length);
						}
						if(sum>=length)break;
					} 
					catch (Exception e) 
					{
						e.printStackTrace();break;
					}
				}
				data = out.toByteArray();
				out.close();
				//imgResponse.setImage(BitmapFactory.decodeStream(in));
				imgResponse.setData(data);
				imgResponse.setSize(length);
				LocalImageManager.saveImage(Tools.getMD5(url), imgResponse.getData());
				
				if(data != null && data.length > 0)
				{
					imgResponse.setStatus(BaseResponse.RET_CODE_SUCCESS);
				}
			} 
			catch (IOException e) 
			{
				imgResponse.setStatus(-1);
				e.printStackTrace();
			}
			catch(OutOfMemoryError e)
			{
				imgResponse.setStatus(-1);
			}
			return imgResponse;
		}
		
		@Override
		protected AbstractParser createParser() {
			// TODO Auto-generated method stub
			return new ImagePaser(url);
		}
		
		public String url;

        @Override
        protected BaseResponse jsonParse(String json) {
            // TODO Auto-generated method stub
            return null;
        }
	}
	
	protected  ThreadPoolExecutor getThreadPoolExecutor()
	{
		return sExecutor;
	}
}
